<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col>
        <el-row :gutter="10" class="mb8">
          <!-- <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:user:remove']">删除</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-upload2" size="mini" @click="handleImport">上传文件</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-upload2" size="mini" @click="cheshi">测试加密按钮</el-button>
          </el-col> -->
          <!-- <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['system:user:export']">导出</el-button>
          </el-col> -->
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
          <!-- <el-table-column type="selection" width="50" align="center" /> -->
          <el-table-column label="编号" align="center" key="id" prop="id" v-if="columns[0].visible" />
          <el-table-column label="文件名称" align="center" key="fileName" prop="fileName" v-if="columns[1].visible" :show-overflow-tooltip="true" />
          <el-table-column label="条数" align="center" key="num" prop="num" v-if="columns[2].visible" width="120" />
          <el-table-column label="上传时间" align="center" prop="createTime" v-if="columns[3].visible" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
              <el-button size="mini" type="text" icon="el-icon-download" @click="handleDownload(scope.row)">原文件下载</el-button>
              <el-button size="mini" type="text" icon="el-icon-download" @click="handleDownExport(scope.row)">结果文件下载</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
      </el-col>
    </el-row>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!-- <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
          </div> -->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <!-- <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link> -->
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as XLSX from 'xlsx';
import { listFile, delFile, ceFile,ceFile1, addFile, downExport} from "@/api/merchant/file";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "User",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 表单参数
      form: {},
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        // url: process.env.VUE_APP_BASE_API + "/system/file/importData",//单个上传
        // url: process.env.VUE_APP_BASE_API + "/system/file/uploadData",//废弃批量上传
        url: process.env.VUE_APP_BASE_API + "/system/prsp/importExcel",//批量上传
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        delFlag:0,
        orderByColumn: 'id',
        isAsc: 'DESC'
      },
      // 列信息
      columns: [
        { key: 0, label: `编号`, visible: true },
        { key: 1, label: `文件名称`, visible: true },
        { key: 2, label: `条数`, visible: true },
        { key: 3, label: `上传时间`, visible: true }
      ],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // :before-upload="beforeUpload"
    beforeUpload(file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: 'array' });
        let totalRows = 0;
        workbook.SheetNames.forEach(sheetName => {
          const XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
          totalRows += XL_row_object.length;
        });
        console.log('totalRows=',totalRows)
        if (totalRows > 100000) { // 例如限制最多1000条数据
          this.$message.error('文件中的数据条数超过限制！');
          return false; // 阻止上传
        } else {
          // 继续上传逻辑
          return true; // 允许上传
        }
      };
      reader.readAsArrayBuffer(file);
    },
    cheshi(){
      // ceFile({fileId:'50'}).then(response => {

      // });
      // ceFile1({fileId:'50',requestId:'393452288238206976'}).then(response => {

      // });
      ceFile1({destDir:"C:\\Users\\cltrl\\Documents\\WeChat Files\\wxid_9r4yh0dj96j722\\FileStorage\\File\\2025-03\\test"}).then(response => {

      });
    },
    /** 列表 */
    getList() {
      this.loading = true;
      listFile(this.queryParams).then(response => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id || this.ids;
      this.$modal.confirm('是否确认删除编号为"' + id + '"的数据项？').then(function() {
        return delFile(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport(row) {
      // this.download('system/user/export', {
      //   ...this.queryParams
      // }, `user_${new Date().getTime()}.xlsx`)
      // this.download(row.filePath, {
      // }, `${row.fileName}`)
      // this.download('/common/download', {
      // }, `user_template_${new Date().getTime()}.xlsx`)
    },
    /** 下载操作 */
    handleDownload(row){
      var name = row.fileName;
      var url = row.filePath;
      this.$download.resource(url,false)
    },
    handleDownExport(row){
      // 1:执行中
      // 2:查询完成
      // -1:执行失败
      // 0:无效的任务id
      // 3:排队中
      if(row.taskStatus == 2){
        this.download('system/prsp/export', {
          fileId:row.id
        }, `${new Date().getTime()}.xlsx`)
      }else if(row.taskStatus == 1){
        this.$message.error('执行中！');
      }else if(row.taskStatus == '-1'){
        this.$message.error('执行失败！');
      }else if(row.taskStatus == '0'){
        this.$message.error('无效的任务id！');
      }else if(row.taskStatus == '3'){
        this.$message.error('排队中！');
      }else{
        this.$message.error('等待中！');
      }
      // downExport({
      //   fileId:row.fileId
      // }).then(response => {
      // });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "上传文件";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      // this.download('system/user/importTemplate', {
      // }, `user_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      console.log(response)
      console.log(file)
      console.log(fileList)
      // var str={
      //   'fileName':response.originalFilename,
      //   // 'filePath':response.url,
      //   'filePath':response.fileName
      // }
      // var params = JSON.stringify(str)
      // addFile(params).then(response => {
        this.getList();
      // });
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
